import { controller, get, post } from '../decorator/route'
import config from '../config'
import reply from '../wechat-cli/reply'
import wechatMiddle from '../wechat-cli/wechatMiddle'

const { wechatCli, wechatOauth } = require('../wechat') 
const wechat = wechatCli()
const oauth = wechatOauth()


@controller('')
export class WechatController {
  @get('/wechat-hear')
  async wechatHearGet(ctx, next) {
    const middle = await wechatMiddle(config.wechat, reply)
    await middle(ctx, next)
  }

  @post('/wechat-hear')
  async wechatHearPost(ctx, next) {
    const middle = await wechatMiddle(config.wechat, reply)
    await middle(ctx, next)
  }

  @get('/signature')
  async wechatSignature(ctx, next) {
    let url = ctx.query.url
    if (!url) ctx.throw(404)
    const data = await wechat.fetchAccessToken()
    const token = data.access_token
    const ticketData = await wechat.fetchTicket(token)
    const ticket = ticketData.ticket
    let params = await wechat.sign(ticket, url)
    params.appId = config.wechat.appID
    ctx.body = {
      success: true,
      data: params
    }
  }

  
  @get('/redirect')
  async redirect(ctx, next) {
    let url = ctx.query.url
    url = encodeURIComponent(url)
    const {a, b} = ctx.query
    const state = `${a}_${b}`
    const authUrl = await oauth.getAuthorizeURL('snsapi_userinfo', url, state)
    ctx.redirect(authUrl)
  }
  
  @get('/oauth')
  async wechatOauth(ctx, next) {
    const {state, code} = ctx.query
    const data = await oauth.fetchAccessToken(code)
    const userinfo = await oauth.getUserInfo(data.access_token, data.openid)
    ctx.body = {
      success: true,
      data: userinfo
    }
  }
}  